﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;

namespace CoreRay
{
    public class PluginManager
    {
        private List<CoreRayPlugin> plugins;

        public PluginManager()
        {
            this.plugins = new List<CoreRayPlugin>();
        }

        public IEnumerable<CoreRayPlugin> Plugins
        {
            get
            {
                return this.plugins;
            }
        }

        public void ScanPluginsFolder()
        {
            if (Directory.Exists("plugins"))
            {
                foreach (string file in Directory.GetFiles("plugins", "*.dll"))
                {
                    try
                    {
                        Assembly assembly = Assembly.LoadFrom(Path.GetFullPath(file));

                        foreach (Type type in assembly.GetExportedTypes())
                        {
                            if (type.IsSubclassOf(typeof(CoreRayPlugin)))
                            {
                                CoreRayPlugin plugin = (CoreRayPlugin)assembly.CreateInstance(type.FullName);

                                if (plugin.CheckCompatibility())
                                {
                                    plugin.Init(CoreRayContext.Current);
                                    this.plugins.Add(plugin);
                                }
                            }
                        }
                    }

                    catch (BadImageFormatException)
                    {
                        continue;
                    }
                }
            }
        }
    }
}
